package cn.devzyh.oms.coms.order.service;

import cn.devzyh.oms.common.core.constant.SecurityConstants;
import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.coms.api.order.dto.OrderDTO;
import cn.devzyh.oms.coms.api.order.entity.OrderDetail;
import cn.devzyh.oms.coms.api.order.entity.OrderHeader;
import cn.devzyh.oms.coms.flow.context.FlowContext;
import cn.devzyh.oms.coms.flow.executor.FlowNode;
import cn.devzyh.oms.wsms.api.constant.StockConstants;
import cn.devzyh.oms.wsms.api.dto.StockDTO;
import cn.devzyh.oms.wsms.api.entity.Stock;
import cn.devzyh.oms.wsms.api.feign.RemoteStockService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 分配库存工作流节点
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AllocateStockNode implements FlowNode {

	private final RemoteStockService remoteStockService;

	private final OrderDetailService orderDetailService;

	@Override
	public R process(FlowContext ctx) {
		OrderDTO order = (OrderDTO) ctx.getMainCache();
		OrderHeader header = order.getHeader();

		for (OrderDetail detail : order.getDetails()) {
			StockDTO dto = new StockDTO();
			dto.setWarehouseCode(header.getWarehouseCode());
			dto.setChannelCode(header.getSourcePlatformCode());
			dto.setSkuCode(detail.getSkuCode());
			dto.setLocation(StockConstants.Location.AVAILABLE);
			dto.setQuantity(detail.getQuantity());
			dto.setDataKey(header.getId().toString());
			R<Stock> res = remoteStockService.allocate(dto, SecurityConstants.FROM_IN);
			if (res.failure()) {
				return res;
			} else {
				Long stockId = res.getData().getId();
				detail.setStockId(stockId);
				LambdaUpdateWrapper<OrderDetail> wrapper = Wrappers.lambdaUpdate();
				wrapper.set(OrderDetail::getStockId, stockId);
				wrapper.eq(OrderDetail::getId, detail.getId());
				orderDetailService.update(wrapper);
			}
		}

		return R.ok();
	}

}
